<template>
  <a-modal
    v-model:open="visible"
    :width="500"
    :confirm-loading="loading"
    ok-text="删除"
    cancel-text="取消"
    ok-type="danger"
    @ok="handleConfirm"
    @cancel="handleCancel"
  >
    <div class="delete-content">
      <div class="warning-icon">
        <AlertTriangle />
      </div>
      
      <div class="delete-info">
        <h3 class="delete-title">确认删除角色？</h3>
        <p class="delete-description">
          您即将删除角色 <strong>"{{ role?.roleName }}"</strong>，此操作不可撤销。
        </p>
        
        <div v-if="role" class="role-preview">
          <div class="role-avatar">
            <a-avatar 
              :size="48" 
              :src="role.avatarUrl || role.avatar"
              :style="{ 
                background: role.avatarUrl || role.avatar ? 'transparent' : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                fontSize: '20px',
                fontWeight: '600'
              }"
              :shape="'square'"
            >
              {{ !role.avatarUrl && !role.avatar ? (role.roleName?.[0] || 'R') : '' }}
            </a-avatar>
          </div>
          <div class="role-details">
            <div class="role-name">{{ role.roleName }}</div>
            <div class="role-tags">
              <!-- 音色标签 -->
              <a-tag
                v-if="role.voiceId"
                size="small"
                color="purple"
                class="role-tag voice-tag"
              >
                <template #icon>
                  <span class="voice-icon">🎵</span>
                </template>
                {{ getVoiceName(role.voiceId) }}
              </a-tag>
              
              <!-- 知识库标签 -->
              <a-tag
                v-if="role.knowledgeId"
                size="small"
                color="blue"
                class="role-tag knowledge-tag"
              >
                <template #icon>
                  <span class="knowledge-icon">📚</span>
                </template>
                {{ getKnowledgeName(role.knowledgeId) }}
              </a-tag>
              
       
            </div>
          </div>
        </div>
        
        <div class="confirmation-input">
          <p class="input-label">
            请输入角色名称 <strong>"{{ role?.roleName }}"</strong> 以确认删除：
          </p>
          <a-input
            v-model:value="confirmText"
            placeholder="请输入角色名称"
            size="large"
            :status="confirmError ? 'error' : ''"
          />
          <div v-if="confirmError" class="error-message">
            角色名称不匹配，请重新输入
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { AlertTriangle } from 'lucide-vue-next'
import roleService, { type ExtendedRole } from '@/api/roleService'
import { useResourceStore } from '@/stores'
import { useAuthStore } from '@/stores/modules/auth'

// Props 和 Emits
interface Props {
  open: boolean
  role?: ExtendedRole | null
}

interface Emits {
  'update:open': [value: boolean]
  'success': [roleId: string]
}

const props = withDefaults(defineProps<Props>(), {
  open: false,
  role: null
})

const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const confirmText = ref('')
const confirmError = ref(false)
const authStore = useAuthStore()
const resourceStore = useResourceStore()

// 计算属性
const canDelete = computed(() => {
  return confirmText.value === props.role?.roleName
})

// 监听 props 变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
  if (newVal) {
    resetForm()
  }
})

watch(visible, (newVal) => {
  emit('update:open', newVal)
  if (!newVal) {
    resetForm()
  }
})

watch(confirmText, () => {
  if (confirmError.value) {
    confirmError.value = false
  }
})

// 方法
const resetForm = () => {
  confirmText.value = ''
  confirmError.value = false
}



const handleConfirm = async () => {
  if (!props.role) return
  
  if (!canDelete.value) {
    confirmError.value = true
    message.error('请正确输入角色名称以确认删除')
    return
  }
  
  try {
    loading.value = true
    
    // 调用真实API删除角色
    await roleService.deleteRole(props.role.id!)
    
    emit('success', props.role.id!)
    message.success(`角色 "${props.role.roleName}" 已删除`)
    visible.value = false
  } catch (error) {
    console.error('删除角色失败:', error)
    
    // 根据错误类型提供更具体的错误信息
    let errorMessage = '删除失败，请重试'
    
    if (error instanceof Error) {
      // 如果是网络错误
      if (error.message.includes('网络') || error.message.includes('连接')) {
        errorMessage = '网络连接失败，请检查网络后重试'
      }
      // 如果是权限错误
      else if (error.message.includes('权限') || error.message.includes('401') || error.message.includes('403')) {
        errorMessage = '没有删除权限，请联系管理员'
      }
      // 如果是服务器错误
      else if (error.message.includes('500') || error.message.includes('服务器')) {
        errorMessage = '服务器错误，请稍后重试'
      }
      // 其他具体错误信息
      else if (error.message && error.message !== '删除角色失败') {
        errorMessage = error.message
      }
    }
    
    message.error(errorMessage)
  } finally {
    loading.value = false
  }
}



const getKnowledgeName = (knowledgeId: string): string => {
  return resourceStore.getKnowledgeBaseName(knowledgeId)
}

const getVoiceName = (voiceId: string): string => {
  return resourceStore.getVoiceName(voiceId) || '默认音色'
}



const handleCancel = () => {
  visible.value = false
}

// 初始化
onMounted(async () => {
  await resourceStore.initResource()
})
</script>

<style scoped>
.delete-content {
  display: flex;
  gap: 16px;
  padding: 8px 0;
}

.warning-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff2f0;
  border-radius: 50%;
  color: #ff4d4f;
  font-size: 24px;
}

.delete-info {
  flex: 1;
}

.delete-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.delete-description {
  margin: 0 0 16px 0;
  color: #666;
  line-height: 1.5;
}

.role-preview {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.role-avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  overflow: hidden;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.role-details {
  flex: 1;
  min-width: 0;
}

.role-name {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.role-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.role-era {
  font-size: 12px;
  color: #999;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.role-tag {
  border-radius: 6px;
  font-size: 12px;
  padding: 2px 8px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.voice-tag {
  background: linear-gradient(135deg, #8b5cf6, #a855f7);
  border: 1px solid #8b5cf6;
  color: white;
}

.voice-icon {
  margin-right: 2px;
  font-size: 10px;
}

.knowledge-tag {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border: 1px solid #3b82f6;
  color: white;
}

.knowledge-icon {
  margin-right: 2px;
  font-size: 10px;
}

.more-tags {
  font-size: 12px;
  color: #999;
}

.confirmation-input {
  margin-top: 16px;
}

.input-label {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
}

.error-message {
  margin-top: 4px;
  font-size: 12px;
  color: #ff4d4f;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .delete-content {
    flex-direction: column;
    text-align: center;
  }
  
  .role-preview {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .role-details {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .role-meta,
  .role-tags {
    justify-content: center;
  }
}
</style>